package photobox.manage

import grails.transaction.Transactional
import grails.validation.ValidationException
import photobox.exception.NotFoundException
import photobox.utils.HQLUtils
import photobox.utils.PermUtils
import photobox.photo.Category
@Transactional
class CategoryService {

    def listCategory(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from Category A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.name) {
            hql += " and " + HQLUtils.whereCondition("A.name", searchParam.name.opt, "name")
            params.name = searchParam.name.data
        }
        if (searchParam.remark) {
            hql += " and " + HQLUtils.whereCondition("A.remark", searchParam.remark.opt, "remark")
            params.remark = searchParam.remark.data
        }
        if (searchParam.categoryType) {
            hql += " and " + HQLUtils.whereCondition("A.categoryType", searchParam.categoryType.opt, "categoryType")
            params.categoryType = searchParam.categoryType.data
        }
        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = Category.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = Category.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def createCategory(params) {
        println(params.categoryType)
        Category category = new Category()
        category.name  = params.name?.trim()
        category.remark = params.remark?.trim()
        category.categoryType =Integer.parseInt(params.categoryType)

        if (!category.save()) {
            println(category.errors)
            throw new ValidationException("创建图片分类时发生错误", category.errors)
        }
    }
    def updateCategory(params) {
        def category = Category.get(params.id as Long)
        if (!category) {
            throw new NotFoundException("没有找到对应的图片分类")
        }
        category.name  = params.name?.trim()
        category.remark = params.remark?.trim()
        category.categoryType =Integer.parseInt(params.categoryType)
        if (!category.save()) {
            throw new ValidationException("创建图片分类时发生错误", category.errors)
        }
    }

    def deleteCategory(params) {
        def category = Category.get(params.id as Long)
        if (!category) {
            throw new NotFoundException("没有找到对应的图片分类")
        }
        category.delete()
    }
}
